package com.zzq.base.awesome.filter;

import com.zzq.base.awesome.component.UserCache;
import com.zzq.base.awesome.entity.MessageInfo;
import com.zzq.base.awesome.entity.SingleObject;
import com.zzq.base.awesome.utils.JwtTokenUtils;
import com.zzq.base.awesome.utils.StringTypeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.zzq.base.awesome.entity.CommonData.JWTPREFIX;
import static com.zzq.base.awesome.entity.CommonData.TOKENTAG;

@Order(2)
@WebFilter(filterName = "authFilter", urlPatterns = "/*")
@Slf4j
public class AuthFilter implements Filter {

    @Autowired
    private UserCache userCache;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String url = servletRequest.getRequestURI();
        String method = servletRequest.getMethod();
        log.info("request url: " + url);
        log.info("request method: " + method);
        if (StringTypeUtil.isIgnoreUrl(url)) {
            log.info("对外开放的url");
            chain.doFilter(request, response);
        } else {
            String token = servletRequest.getHeader(TOKENTAG);
            if (token == null) {
                log.info("token 为空");
                HttpServletResponse servletResponse = (HttpServletResponse) response;
                servletResponse.sendError(401, "token不能为空");
                return;
            }
            if (!token.startsWith(JWTPREFIX)) {
                log.info("token不以" + JWTPREFIX + "开头");
                HttpServletResponse servletResponse = (HttpServletResponse) response;
                servletResponse.sendError(401, "token的格式不正确");
                return;
            }
            token = StringUtils.substringAfter(token, JWTPREFIX);
            if (!JwtTokenUtils.isJwtOk(token)) {
                HttpServletResponse servletResponse = (HttpServletResponse) response;
                log.info("token验证未通过");
                servletResponse.sendError(401, "token验证未通过");
                return;
            }
            String id = JwtTokenUtils.getUserId(token);
            if (userCache.isUserIn(id)) {
                log.info("用户未登录");
                HttpServletResponse servletResponse = (HttpServletResponse) response;
                servletResponse.sendError(401, "用户未登录");
                return;
            }
            chain.doFilter(request, response);
        }
    }
}
